<!-- 支出单批量付款确认费用 -->
<template>
  <a-modal
    v-model:visible="showModal"
    @close="onClose"
    @before-ok="submitFn"
    title="批量付款"
    class="modal-dialog-wrapper"
    unmount-on-close
    :mask-closable="false"
    width="97vw"
  >
    <div class="fee-page">
      <table-index :table="table">
        <template #code="{ record }">
          <div class="order-info-item">
            <div>{{ record.costTypeName }}</div>
            <div>{{ record.code }}</div>
          </div>
        </template>
        <!-- 支出费项 -->
        <template #feeList="{ record }">
          <template v-for="(item, index) in record.feeList" :key="index">
            {{ item.itemName }}
            <div class="td-divider" v-if="index != record.feeList.length - 1"></div>
          </template>
        </template>
        <!-- 费用金额 -->
        <template #feeAmount="{ record }">
          <div v-for="(item, index) in record.feeList" :key="index">
            <span> {{ item.amount }} </span>
            <div class="td-divider" v-if="index != record.feeList.length - 1"></div>
          </div>
        </template>
        <!-- 车辆信息 -->
        <template #carInfo="{ record }">
          <template v-for="(item, index) in record.feeList" :key="index">
            <div class="flex">
              <div class="carLicenseNo">{{ item.carId ? `${item.licenseNo}` : '-' }}</div>
            </div>
            <div class="td-divider" v-if="index != record.feeList.length - 1"></div>
          </template>
        </template>
        <!-- 付款时间 -->
        <template #payTime="{ record }">
          <span>{{ record.payTime || '-' }}</span>
        </template>
        <!-- 收款方信息 -->
        <template #collectInfo="{ record }">
          <div v-if="record.costType == 1">
            <p>收款方：{{ record.collectStaffName }}</p>
            <p>方式：{{ record.collectInExpWayName || '-' }}</p>
            <p>账号：{{ record.collectCard }}</p>
          </div>
          <template v-else>
            <div>
              <p>收款方：{{ record.collectType == 2 ? record.collectIndustryName : record.collectSupplierName }}</p>
              <p>方式：{{ record.collectInExpWayName || '-' }}</p>
              <p>账号：{{ record.collectCard }}</p>
            </div>
          </template>
        </template>
      </table-index>
      <div class="count-total"> 合计： {{ unitVal(countTotal, '元') }}</div>

      <a-divider class="custom-divider" />

      <page-form :model="form" layout="vertical" ref="formRef">
        <page-form-row>
          <page-form-item field="payTime" label="付款时间" :rules="[{ required: true, message: '请选择付款时间', trigger: 'change' }]">
            <i-date-picker class="w-full" v-model="form.payTime" show-time value-format="YYYY-MM-DD HH:mm:ss" popup-container=".fee-page" />
          </page-form-item>
          <page-form-item
            field="payWay"
            label="付款方式"
            :rules="{ required: true, message: '请选择付款方式' }"
            labelTooltipContent="收/付款方式支持在系统管理菜单下的收支账号管理页面进行配置。"
          >
            <a-select placeholder="请选择" v-model="form.payWay" @change="typeChange" popup-container=".fee-page">
              <a-option v-for="item in paywayEnum" :key="item.way" :value="item.way" :label="item.wayStr" />
            </a-select>
          </page-form-item>
          <page-form-item
            field="payAccountId"
            label="付款账号"
            labelTooltipContent="收/付款账号支持在系统管理菜单下的收支账号管理页面进行配置。"
          >
            <a-select
              :placeholder="!form.payWay ? '请先选择付款方式' : '请选择'"
              v-model="form.payAccountId"
              :disabled="!form.payWay ? true : false"
              popup-container=".fee-page"
            >
              <a-option
                v-for="item in accountList"
                :key="item.id"
                :value="item.id"
                :label="item.account + (item.bank ? '_' + item.bank : '')"
              />
            </a-select>
          </page-form-item>
          <page-form-item label="付款金额">
            <i-input-number disabled v-model="countTotal" unit="元" :precision="2" />
          </page-form-item>
          <page-form-item label="财务打款备注" size="2/3">
            <a-textarea class="w-full" placeholder="请输入" :max-length="400" v-model="form.payRemark" auto-size />
          </page-form-item>
        </page-form-row>
        <page-form-row>
          <page-form-item label="打款凭证（支持上传jpg、png格式，最多上传10张）" size="1">
            <upload-img v-model="form.payFileIdList" :limit="10" />
          </page-form-item>
        </page-form-row>
      </page-form>
    </div>
    <template #footer>
      <a-space>
        <a-button @click="onClose">关闭</a-button>
        <a-button type="primary" @click="submitFn">确认</a-button>
      </a-space>
    </template>
  </a-modal>
  <!-- 费用明细弹框 -->
  <fee-item-modal ref="feeItemModalRef" />
</template>

<script setup name="OperateCostConfirmAllFees">
  import { ref, reactive, computed } from 'vue'
  import { Message } from '@arco-design/web-vue'
  import { useTable } from '@/hooks/table'
  import feeItemModal from './fee-item-modal.vue'
  import decimal from '@/utils/calculation'
  import { unitVal } from '@/utils'
  import { getAccountByPageData, getAccountByWayAndType } from '@/api/order/sOrder'
  import { getAllFeeListApi, payCostApi, batchPayApi } from '@/api/business/operateCost'

  const paywayEnum = ref([]) //收付款方式
  const accountList = ref([]) //收付款账号列表

  const formRef = ref(null)
  const form = ref({})
  const queryParam = reactive({})
  // 打开弹窗
  const showModal = ref(false)
  const show = (val) => {
    // 重置
    resetForm()
    getType()
    showModal.value = true
    form.value.idList = val
    queryParam.idList = val
    loadData()
  }
  const onClose = () => {
    showModal.value = false
  }
  const resetForm = () => {
    paywayEnum.value = []
    accountList.value = []
    form.value = {}
  }

  const feeItemModalRef = ref()
  const operates = computed(() => {
    return [
      {
        label: '详情',
        method: (record) => {
          feeItemModalRef.value.open(record)
        },
      },
    ]
  })

  // table 配置
  const table = useTable({
    columns: [
      { title: '支出单信息', slotName: 'code', width: 180, fixed: 'left' },
      { title: '收款方信息', slotName: 'collectInfo', width: 240 },
      { title: '费用产生门店', dataIndex: 'feeOrgName', width: 150, ellipsis: true },
      { title: '支出单总金额', dataIndex: 'amount', unit: '元', width: 150 },
      { title: '费项明细', slotName: 'feeList', width: 110 },
      { title: '费项金额', slotName: 'feeAmount', unit: '元', width: 120 },
      { title: '车牌号', slotName: 'carInfo', width: 110 },
      { title: '申请时间', dataIndex: 'applyTime', width: 190 },
    ],
    bordered: {
      wrapper: true,
      cell: true,
    },
    dataList: [],
    pagination: false,
    tableLoading: false,
    operates: operates.value,
  })

  const loadData = () => {
    table.tableLoading = true
    getAllFeeListApi(queryParam)
      .then((res) => {
        const result = res.result
        var data = result.data
        table.dataList = data
      })
      .finally(() => {
        table.tableLoading = false
      })
  }
  // 收付款类型
  const getType = () => {
    getAccountByPageData({ type: 1 }).then((res) => {
      // 过滤
      var data = res.result
      data.forEach((i) => {
        // 付款方式中的枚举需要过滤网络平台代收、网络平台待付、微信线上支付、押金抵扣、预授权
        if (i.way != '1' && i.way != '2' && i.way != '3' && i.way != '4' && i.way != '5') {
          paywayEnum.value.push(i)
        }
      })
      if (form.value.payWay) {
        typeChange(form.value.payWay)
      }
    })
  }
  // 账号
  const typeChange = (e) => {
    if (e) {
      form.value.payAccountId = ''
    }
    paywayEnum.value.forEach((el) => {
      if (el.way == e) {
        getAccountByWayAndType({ way: Number(el.way), type: 1 }).then((res) => {
          accountList.value = res.result
        })
      }
    })
  }
  // 计算金额
  const countTotal = computed(() => {
    let total = 0
    table.dataList.forEach((item) => {
      total = decimal.add(total, item.amount || 0)
    })
    return total
    // return unitVal(total, '元')
  })

  defineExpose({
    show,
  })
  const emit = defineEmits(['feepageConfirm'])
  const validateFormFn = () => {
    return new Promise((resolve, reject) => {
      formRef.value.validate((error) => {
        if (error) {
          reject()
        } else {
          resolve()
        }
      })
    })
  }
  // 确认提交付款
  const submitFn = () => {
    return new Promise((resolve, reject) => {
      validateFormFn()
        .then(() => {
          const param = {
            id: form.value.idList[0],
            idList: form.value.idList,
            payTime: form.value.payTime,
            payWay: form.value.payWay,
            payAccountId: form.value.payAccountId,
            payFileIdList: form.value.payFileIdList,
            payRemark: form.value.payRemark,
          }
          let fetch = form.value.idList.length > 1 ? batchPayApi : payCostApi
          fetch(param)
            .then((res) => {
              Message.success(res.message)
              showModal.value = false
              emit('feepageConfirm')
            })
            .catch(() => {
              reject()
            })
        })
        .catch(() => {
          reject()
        })
    })
  }
</script>

<style lang="less" scoped>
  .fee-list {
    padding-top: 20px;
    border: 1px solid #f2f3f5;
    .fee-tlt {
      width: 100%;
      height: 40px;
      background-color: #f2f3f5;
      display: flex;
      justify-content: space-between;
      align-items: center;
      .tlt-name {
        .tag-name {
          font-weight: 600;
          font-size: 14px;
          margin-left: 20px;
        }
      }
      .tlt-price {
        font-size: 14px;
        color: #1890ff;
        font-weight: 600;
        margin-right: 20px;
      }
    }
    .fee-msg {
      background: #fbfbfc;
      display: flex;
      justify-content: space-between;
      align-items: flex-start;
      width: 100%;
      padding-top: 20px;
      .msg {
        flex: 1;
        display: flex;
        justify-content: flex-start;
        align-items: center;
        flex-wrap: wrap;
        margin-left: 20px;
        div {
          width: 33.33%;
          margin-bottom: 12px;
        }
        .msg-tlt {
          color: var(--color-neutral-10);
          span {
            color: var(--color-neutral-8);
          }
        }
        .times {
          width: 66.66%;
        }
      }
      .msg-open {
        color: #1890ff;
        font-size: 14px;
        margin-right: 20px;
        cursor: pointer;
      }
    }
    .line {
      width: 100%;
      background-color: #fbfbfc;
      div {
        width: calc(100% - 40px);
        margin-left: 20px;
        height: 1px;
        background-color: #f2f3f5;
      }
    }
    .amount-all {
      background-color: #fbfbfc;
      .amount {
        width: 100%;
        height: 62px;
        display: flex;
        justify-content: flex-end;
        align-items: center;
        padding-right: 20px;
      }
    }
    .fee-table {
      background: #fbfbfc;
      padding: 24px;
      width: 100%;
      .table-items {
        .item-row {
          display: flex;
          justify-content: flex-start;
          align-items: center;
          .item-pro {
            font-weight: 600;
            width: 200px;
            margin-bottom: 12px;
            cursor: pointer;
          }
          .item-pro-twice {
            font-weight: 400;
            margin-left: 14px;
          }
          .open-icon {
            margin-left: 2px;
          }
          .open-icon-close {
            transform: rotate(180deg);
          }
          .item-name {
            width: 30%;
          }
          .item-cost {
            width: 15%;
          }
          .item-amount {
            width: 15%;
            font-weight: 400;
          }
          .item-remark {
            width: 40%;
            overflow: hidden;
            text-overflow: ellipsis;
            -webkit-line-clamp: 1;
            display: -webkit-box;
            -webkit-box-orient: vertical;
          }
        }
      }
    }
  }
  .all-cost {
    font-weight: 600;
    padding: 20px;
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    background: #f2f3f5;
    height: 100px;
    .cost-num {
      color: #1890ff;
      display: flex;
      flex-direction: column;
      align-items: flex-end;
    }
  }
  // 弹窗添加的样式
  .fee-page {
    width: 100%;
    max-height: 70vh;
    position: relative;

    :deep(.arco-row) {
      margin-left: 0 !important;
      margin-right: 0 !important;
    }
    :deep(.arco-modal-body) {
      padding: 10px 80px !important;
    }
    :deep(.arco-col) {
      padding: 0 10px !important;
    }
  }
  .count-total {
    border: 1px solid #f2f3f5;
    border-top: none;
    width: 100%;
    text-align: center;
    padding: 10px 0;
    color: #1890ff;
    font-weight: 500;
    font-size: 16px;
  }
</style>
